﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Movement;
using RPG.Core;

namespace RPG.Combat
{
    public class Fighter : MonoBehaviour, IAction
    {
        Transform targetTrans;
        [SerializeField] float range = 2.0f;
        [SerializeField] float timeBetweenAttack = 2.0f;
        [SerializeField] float weaponDamge = 5.0f;
        float timeSinceAfterAttack = Mathf.Infinity;

        private void Update() {
            if (targetTrans)
            {
                if (targetTrans.GetComponent<Health>().IsDead())
                {
                    return;
                }

                if (Vector3.Distance(transform.position, targetTrans.position) > range)
                {
                    GetComponent<Mover>().MoveTo(targetTrans.position);
                }
                else
                {
                    GetComponent<Mover>().Cancel();
                    timeSinceAfterAttack += Time.deltaTime;
                    if (timeBetweenAttack < timeSinceAfterAttack)
                    {
                        AttackBehaviour();
                        timeSinceAfterAttack = 0;
                    }
                }
            } 
        }

        private void AttackBehaviour()
        {
            transform.LookAt(targetTrans);
            TriggerAttack();
            // targetTrans.GetComponent<Health>().TakeDamage(weaponDamge);
        }

        private void TriggerAttack()
        {
            GetComponent<Animator>().ResetTrigger("stopAttack");
            GetComponent<Animator>().SetTrigger("attack");
        }

        public bool CanAttack(GameObject target)
        {
            return target.transform !=null && !target.transform.GetComponent<Health>().IsDead();
        }

        public void Attack(GameObject target)
        {
            // print("Take that you short, squat peasnat!");
            GetComponent<ActionScheduler>().StartAction(this);
            targetTrans = target.transform;
        } 

        public void Cancel()
        {
            StopAttack();
            targetTrans = null;
        }

        private void StopAttack()
        {
            GetComponent<Animator>().ResetTrigger("attack");
            GetComponent<Animator>().SetTrigger("stopAttack");
        }

        void Hit()
        {
            if (targetTrans == null) return;
            targetTrans.GetComponent<Health>().TakeDamage(weaponDamge);
        }
    }
}

